package net.mayee.alice.spring.interceptor;

import jodd.props.Props;
import net.mayee.alice.common.Definiens;
import net.mayee.alice.filter.ShiroAdminDbRealm;
import net.mayee.alice.spring.exception.AliceLockScreenException;
import net.mayee.common.AliceHelper;
import net.mayee.common.MenuHelper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CoreInterceptor extends HandlerInterceptorAdapter {

    private String urlPrefix = null;

    {
        Props props = AliceHelper.getInstance().getJoddProps();
        urlPrefix = props.getValue("menu.url.prefix");
    }

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String requestURL = request.getRequestURL().toString();
        if(requestURL.indexOf(urlPrefix + "/") > 0){
            MenuHelper.getInstance().buildActiveSidebarMenu(request.getServletPath());
        }

        Subject currentUser = SecurityUtils.getSubject();
        ShiroAdminDbRealm.ShiroUser shiroUser = (ShiroAdminDbRealm.ShiroUser) currentUser.getPrincipal();
        if(shiroUser != null && requestURL.indexOf("/sdm/prof/lockS") < 0){
            if(shiroUser.getIsLockScreen() == Definiens.STATUS_CODE_LOCKSCREEN){
                throw new AliceLockScreenException();
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
    }

}
